// App.tsx
import React, { useState } from 'react';
import { Upload, Button, message, Spin } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { RcFile } from 'antd/lib/upload';
import './App.css';

const App: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [markdown, setMarkdown] = useState('');

  const handleUpload = async (file: RcFile) => {
    setLoading(true);
    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await fetch('http://localhost:8000/convert', {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        throw new Error('转换失败');
      }

      const data = await response.json();
      setMarkdown(data.content);
      message.success('转换成功！');
    } catch (error) {
      message.error('转换失败：' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const beforeUpload = (file: RcFile) => {
    const isPDF = file.type === 'application/pdf';
    if (!isPDF) {
      message.error('只能上传 PDF 文件！');
      return false;
    }
    handleUpload(file);
    return false;
  };

  const copyToClipboard = () => {
    navigator.clipboard.writeText(markdown)
      .then(() => message.success('已复制到剪贴板'))
      .catch(() => message.error('复制失败'));
  };

  return (
    <div className="container">
      <h1>PDF 转 Markdown 工具</h1>
      <div className="upload-section">
        <Upload
          beforeUpload={beforeUpload}
          showUploadList={false}
        >
          <Button icon={<UploadOutlined />}>选择 PDF 文件</Button>
        </Upload>
      </div>

      <Spin spinning={loading}>
        {markdown && (
          <div className="result-section">
            <div className="toolbar">
              <Button onClick={copyToClipboard}>复制内容</Button>
            </div>
            <div className="markdown-preview">
              <pre>{markdown}</pre>
            </div>
          </div>
        )}
      </Spin>
    </div>
  );
};

export default App;